package me.xue.communityhealth.service;

import com.github.pagehelper.Page;
import lombok.extern.log4j.Log4j2;
import me.xue.communityhealth.exception.ObjectNotFoundException;
import me.xue.communityhealth.model.Drug;
import me.xue.communityhealth.repo.DrugRepository;
import me.xue.communityhealth.util.ApplicationUtil;
import me.xue.communityhealth.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@Service
@Log4j2
public class DrugService implements BaseService<Drug, Integer> {

    private final DrugRepository drugRepository;

    @Autowired
    public DrugService(DrugRepository drugRepository) {
        this.drugRepository = drugRepository;
    }

    public int save(Drug drug) {
        return drugRepository.save(drug);
    }

    public int update(Drug drug) {
        return drugRepository.update(drug);
    }

    @Override
    public int delete(Integer which) {
        return drugRepository.delete(which);
    }

    @Override
    public List<Drug> findAll() {
        return null;
    }

    public List<Drug> findByAbbreviate(String abbreviate) {
        return drugRepository.findByAbbreviate(abbreviate);
    }

    public Drug findOne(Integer id) {
        Drug drug = drugRepository.findOne(id);
        if (drug == null) {
            throw new ObjectNotFoundException();
        }
        return drug;
    }

    public Page<Drug> pagedDrugs() {
        return drugRepository.pagedDrugs();
    }

    public String savePhoto(MultipartFile multipartFile, String fileName) {
        if (multipartFile == null || multipartFile.isEmpty()) {
            return null;
        }
        return FileUtil.saveMultipartFile(multipartFile, ApplicationUtil.getDrugPath().getAbsolutePath(), fileName);
    }

    public void deletePhoto(String fileName) {
        File file = new File(ApplicationUtil.getDrugPath().getAbsolutePath(), fileName);
        if (file.exists()) {
            try {
                Files.delete(Paths.get(ApplicationUtil.getDrugPath().getAbsolutePath(), fileName));
            } catch (IOException e) {
                log.error("删除药品图片失败", e);
            }
        }
    }

}
